/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package com.cn.recloud.UploadAndDownload;

import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @description:  从minIO中下载文件  存储桶是testwang  存储对象名称是abc.txt
 * @author: wayne Wang
 * @date: 2020/7/30
 */
@RestController
public class FileDownload {

    @Value("${minio.endpoint}")
    private String ENDPOINT;
    @Value("${minio.accesskey}")
    private String ACCESS_KEY;
    @Value("${minio.secretkey}")
    private String SECRET_KEY;

    @GetMapping("download")
    public void downloadFiles(HttpServletResponse httpResponse) {
        String filename = "abc.txt";
        try {
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            InputStream object = minioClient.getObject("testwang", filename);
            byte buf[] = new byte[1024];
            int length = 0;
            httpResponse.reset();
            httpResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            httpResponse.setContentType("application/octet-stream");
            httpResponse.setCharacterEncoding("utf-8");
            OutputStream outputStream = httpResponse.getOutputStream();
            while ((length = object.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            outputStream.close();
        } catch (Exception ex) {
            System.out.println("导出失败：" + ex.getMessage());
        }
    }
}
